<template>
  <div class="inp">
    <input
      type="text"
      placeholder="地图兴趣点搜索"
      @input="debouncedHandleSearch"
      v-model="input"
      style=""
    />
    <span class="search-icon"></span>
    <span class="clear-icon" @click="clearInput"></span>
  </div>
  <div class="inp-list" v-if="flag && input != ''">
    <div class="item" v-for="item in poiData" :key="item" @click="toView(item)">
      <span class="icon"></span>
      <span class="text" :title=" item.distent">{{ item.name }}{{ item.distent }}</span>
    </div>
  </div>

  <div class="tool" ref="tool" @mouseleave="iscom">
    <div
      class="tool-item"
      v-for="(item, index) in toolData"
      :key="item.id"
      @click="switchMap(index)"
    >
      <span class="tool-icon">
        <img :src="item.icon" alt="" style="width: 100%; height: 100%" />
      </span>
      <span class="tool-text">{{ item.title }}</span>
    </div>
    <div class="historyDz" v-show="toolIndex == 0">
      <historyStock @close-time="closeTime" />
    </div>
    <div class="shock-list" v-show="toolIndex == 1">
      <shockList :toolIndex="toolIndex" />
    </div>

    <div class="selectBh" v-show="toolIndex == 3">
      <Plotting />
    </div>
    <div class="specialMap scroll-b" v-show="toolIndex == 2">
      <specialMap />
    </div>

    <div class="xcdc" v-show="toolIndex == 5">
      <xcdc />
    </div>
  </div>

  <div class="tool-b" ref="toolb">
    <div class="home" @click="tohome">
      <div></div>
    </div>
    <div class="pop" @click="toolBIndex === 3 ? (toolBIndex = -1) : (toolBIndex = 3)">
      <img :src="earth2DOr3d ? '/static/assets/3d/地球.png' : '/static/assets/3d/ewm.png'" alt="" />
    </div>
    <div class="item-gj" @click="toolBIndex === 1 ? (toolBIndex = -1) : (toolBIndex = 1)"></div>
    <div class="item-dt" @click="toolBIndex === 2 ? (toolBIndex = -1) : (toolBIndex = 2)"></div>
    <div class="tool-list" v-show="toolBIndex == 1"><toolList /></div>
    <div class="selectMap" v-show="toolBIndex == 2">
      <selectMap />
    </div>

    <div style="display: flex" class="selectMaps" v-show="toolBIndex == 3">
      <div class="t2" :class="earth2DOr3d ? '' : 'active'" @click="to2D">
        <img src="/static/assets/3d/ewm.png" alt="" />
      </div>
      <div class="t3" :class="earth2DOr3d ? 'active' : ''" @click="to3D">
        <img src="/static/assets/3d/dq.png" alt="" />
      </div>
    </div>

    <!-- <div class="addZoom" @click='addZoom'>+</div>
    <div class="eddZoom" @click="eddZoom">-</div> -->
  </div>

  <downImg
    :dialogVisible="dialogVisible"
    @change-flag="dialogVisible = false"
    v-if="dialogVisible"
  />

  <div ref="popup" class="popup">
    <roomDialog
      :isuseDraggable="false"
      size="small"
      :title="poiname"
      :isFixed="false"
      @close="
        () => {
          hidePopup()
        }
      "
    >
      <div v-html="poihtml"></div>
    </roomDialog>
  </div>
</template>

<script setup>
import darkInput from '../../../components/darkInput.vue'
import ycss from './components/ycss.vue'
import screenDialog from '../../../components/screenDialog.vue'
import selectMap from './components/selectMap.vue'
import fileButton from '../../../components/fileButton.vue'
import shockList from './components/shockList.vue'
import toolList from './components/tool/index.vue'
import historyStock from './components/historyStock.vue'
import xcdc from './components/xcdc.vue'
import specialMap from './components/specialMap.vue'
import Plotting from './components/Plotting.vue'
import useDebounce from '../../../hook/useDebounce'
import downImg from './components/downImgDialog.vue'
import {
  createPointAndToView,
  createPopup,
  calculateDistanceWithArrays,toViewEarthQuakeCenter
} from '../../../api/gis3d/maputils'
import { ElMessage } from 'element-plus'
import config from '../../../config'
import { useMapStoreStore } from '../../../stores/index'
const store = useMapStoreStore()

const dialogVisible = ref(false)

const switchMap = (index) => {
  if (index == 4) {
    dialogVisible.value = true
    return
  }
  toolIndex.value = index
}
const activeIndex = ref(-1)
const toolIndex = ref(-1)

const toolData = [
  {
    id: 1,
    title: '历史地震',
    icon: '/static/assets/3d/lsdz.png'
  },
  {
    id: 2,
    title: '余震',
    icon: '/static/assets/3d/yz.png'
  },
  {
    id: 3,
    title: '图层',
    icon: '/static/assets/3d/tc.png'
  },
  {
    id: 4,
    title: '标绘',
    icon: '/static/assets/3d/bh.png'
  },
  {
    id: 5,
    title: '出图',
    icon: '/static/assets/3d/ct.png'
  },
  {
    id: 6,
    title: '现场调查',
    icon: '/static/assets/3d/xcdz.png'
  }
  // {
  //   id: 7,
  //   title: '工具',
  //    icon: '/static/assets/3d/lsdz.png'
  // },
  // {
  //   id: 8,
  //   title: '切换底图',
  //     icon: '/static/assets/3d/lsdz.png'
  // }

  // ,
  // {
  //   id: 9,
  //   title: '渔船筛选',
  //   icon: '/static/icon/poi.png'
  // }
]
const tool = ref(null)

/////  poi  start//////
const input = ref('')
const poiData = ref([])
const flag = ref(false)
const popup = ref(null)
const popupFlag = ref(false)

function getLevel(height) {
  if (height > 48000000) {
    return 1
  } else if (height > 24000000) {
    return 1
  } else if (height > 12000000) {
    return 2
  } else if (height > 6000000) {
    return 3
  } else if (height > 3000000) {
    return 4
  } else if (height > 1500000) {
    return 5
  } else if (height > 750000) {
    return 6
  } else if (height > 375000) {
    return 7
  } else if (height > 187500) {
    return 8
  } else if (height > 93750) {
    return 9
  } else if (height > 46875) {
    return 10
  } else if (height > 23437.5) {
    return 11
  } else if (height > 11718.75) {
    return 12
  } else if (height > 5859.38) {
    return 13
  } else if (height > 2929.69) {
    return 14
  } else if (height > 1464.84) {
    return 15
  } else if (height > 732.42) {
    return 16
  } else if (height > 366.21) {
    return 17
  } else {
    return 18
  }
}

const getData = () => {
  const extend = viewer.camera.computeViewRectangle()
  const minx = Cesium.Math.toDegrees(extend.west)
  const maxx = Cesium.Math.toDegrees(extend.east)
  const maxy = Cesium.Math.toDegrees(extend.north)
  const miny = Cesium.Math.toDegrees(extend.south)
  var alti = viewer.camera.positionCartographic.height
  var level = getLevel(alti)

  const apiUrl = `http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${input.value}","level":${level},"mapBound":"${minx},${miny},${maxx},${maxy}","queryType":2,"start":0,"count":40}&type=query&tk=${config.TDTTK}`
  fetch(apiUrl)
    .then((response) => response.json())
    .then((data) => {
      if (data && data.pois && data.pois.length > 0) {
        var dzCenter = [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude]
        for (const item of data.pois) {
          var a = item.lonlat.split(',')
          var icenter = [Number(a[0]), Number(a[1])]
          item.distent = '(' + calculateDistanceWithArrays(dzCenter, a) + '公里)'
        }

        poiData.value = data.pois
        flag.value = true
      } else {
        ElMessage({
          message: '视野内暂无数据，请缩小范围',
          type: 'warning',
          plain: true
        })
        poiData.value = []
      }
    })
    .catch((error) => {
      ElMessage({
        message: '搜索请求失败',
        type: 'error',
        plain: true
      })
    })
}
let billboardEntity = null
let edit = null
let del = null
let closePopup = null
let hidePopup = null
const poihtml = ref('')
const poiname = ref('')
const debouncedHandleSearch = useDebounce(getData, 1000)
const toView = (e) => {
  const [longitude, latitude] = e.lonlat.split(',')
  const coordinates = [Number(longitude), Number(latitude)]
  if (billboardEntity) {
    edit({ position: coordinates, data: e, type: 'search-poi' })
    hidePopup()
    return
  }
  ;({ billboardEntity, edit, del } = createPointAndToView({
    position: coordinates,
    data: e,
    type: 'search-poi',
    url: '/static/icon/poi.png'
  }))
  ;({ closePopup, hidePopup } = createPopup(popup.value, 65, getPoiData, 'search-poi'))
}
const getPoiData = (data) => {
  var positions = data.lonlat.split(',')
  poiname.value = data.name
  poihtml.value = ` <div class='search-poi' style='  height: 100%; line-height: 30px;font-size:18px'>
      <div>地址:&nbsp;${data.address}</div>
      <div>名称:&nbsp;${data.name}</div>
      <div>经度:&nbsp;${positions[0]}</div>
       <div>纬度:&nbsp;${positions[1]}</div>
    </div>`
}
const clearInput = () => {
  input.value = ''
  billboardEntity = null
  edit = null
  del && del()
  del = null
  closePopup && closePopup()
}
/////  poi  end//////

const toolb = ref(null)
const toolBIndex = ref(-1)

const timeFlag = ref(false)
const iscom = (e) => {
  setTimeout(() => {
    if (toolIndex.value === 0 && timeFlag.value) {
      return
    }
    // toolIndex.value = -1
  }, 100)
}

const closeTime = (e) => {
  timeFlag.value = e
}

const earth2DOr3d = ref(true)
const to2D = () => {
  if (!earth2DOr3d.value) return
  earth2DOr3d.value = false
  map3d.switchViewMode('2')
}
const to3D = () => {
  if (earth2DOr3d.value) return
  earth2DOr3d.value = true
  map3d.switchViewMode('3')
}

const tohome = () => {
  toViewEarthQuakeCenter()
  // var lon = store.earthquakeInfo.longitude
  // var lat = store.earthquakeInfo.latitude
  // viewer.camera.flyTo({
  //   destination: Cesium.Cartesian3.fromDegrees(lon, lat, 151500),
  //   duration: 1 // 飞行时间（s）
  // })
}

const addZoom = () => {
  var camera = viewer.camera
  var currentPosition = camera.position
  var newPosition = new Cesium.Cartesian3(
    currentPosition.x,
    currentPosition.y,
    currentPosition.z * 0.6
  ) // 将相机高度变为原来的0.8倍，可调整该系数
  camera.flyTo({
    destination: newPosition,
    duration: 0.5 // 相机飞行到新位置的时间，单位为秒，可调整
  })
}
const eddZoom = () => {
  var camera = viewer.camera
  var currentPosition = camera.position
  var newPosition = new Cesium.Cartesian3(
    currentPosition.x,
    currentPosition.y,
    currentPosition.z * 1.2
  ) // 将相机高度变为原来的1.2倍，可调整该系数
  camera.flyTo({
    destination: newPosition,
    duration: 0.5
  })
}

onMounted(() => {
  document.addEventListener('click', function (e) {
    const target = e.target
    const toolA = tool.value
    const toolB = toolb.value
    const isInsideTool = toolA && toolA.contains(target)
    const isInsideToolB = toolB && toolB.contains(target)

    if (!isInsideToolB) {
      toolBIndex.value = -1
    }
    if (timeFlag.value) return
    if (!isInsideTool) {
      toolIndex.value = -1
    }
  })
})
onUnmounted(() => {
  closePopup && closePopup()
})
</script>

<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
}
.popup {
  position: fixed;
  display: none; /* 初始隐藏 */
  width: 450px;
  height: 200px;
}
.inp {
  position: relative;
  width: 380px;
  height: 48px;
  background-image: url(/static/assets/3d/inp.png);
  background-size: contain;
  input {
    width: 100%;
    height: 100%;
    background-color: transparent;
    outline: none;
    border: none;
    padding-left: 15px;
    padding-right: 105px;
    font-size: 18px;
    color: #b9eeff;
  }
  input::placeholder {
    color: #b9eeff;
  }
  .search-icon {
    display: inline-block;
    width: 22px;
    height: 22px;
    background-size: contain;
    background-image: url(/static/assets/3d/search.png);
    background-size: 100% 100%;
    position: absolute;
    right: 60px;
    top: 10px;
    z-index: 2;
    cursor: pointer;
  }
  .clear-icon {
    display: inline-block;
    width: 22px;
    height: 22px;
    background-image: url(/static/assets/3d/clear.png);
    background-size: 100% 100%;
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
  }
  .clear-icon:hover {
    transform: rotate(360deg);
    transition: all 1s ease;
  }
  #search {
    width: 100%;
    padding: 0 35px;
    height: 40px;
    background: rgba(0, 25, 51, 0.8);
    border-radius: 4px;
    border: none;
    outline: none;
    color: #b9eeff;
    font-size: 16px;
    &::placeholder {
      color: #b9eeff;
    }
  }
}
.inp-list {
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  color: #fff;
  text-align: center;
  align-items: center;
  cursor: pointer;
  max-height: 500px;
  padding: 10px 0;
  box-sizing: border-box;
  overflow-y: auto;
  width: 380px;
  position: absolute;
  top: 55px;
  left: 0px;
  z-index: 9;
  // 滚动条整体部分
  &::-webkit-scrollbar {
    width: 6px;
    height: 8px;
  }
  &::-webkit-scrollbar-button {
    display: none;
  }
  &::-webkit-scrollbar-thumb {
    background: #01c2ff;
    cursor: pointer;
    border-radius: 4px;
  }
  &::-webkit-scrollbar-corner {
    display: none;
  }
  &::-webkit-resizer {
    display: none;
  }
  .item {
    display: flex;
    align-items: center;
    color: #b9eeff;
    padding: 0 10px;
    box-sizing: border-box;
    cursor: pointer;
    height: 50px;
    width: 100%;
    overflow: hidden;
    border-bottom: 1px solid #b9eeff;

    &:hover {
      background-color: #0b8cbe85;
    }
    .icon {
      width: 32px;
      height: 32px;
      background-image: url(/static/icon/poi.png);
      background-size: 100% 100%;
    }
    .text {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.tool {
  width: 90px;
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: end;
  right: 0;
  color: #fff;
  .selectBhm,
  .historyDz,
  .xcdc,
  .selectBh,
  .shock-list,
  .selectMap,
  .specialMap {
    position: absolute;
    background: rgba(0, 0, 10, 0.8);
    box-sizing: border-box;
    border: 1px solid #0e9cff;
    box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  }
  .tool-item {
    width: 75px;
    height: 87px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding: 5px;
    box-sizing: border-box;
    align-items: center;
    margin-top: 10px;
    cursor: pointer;
    background-image: url(/static/assets/3d/tool.png);
    background-size: 100% 100%;
    font-size: 16px;
    font-weight: 500;

    color: #83dcf9;
    &:hover {
      background-color: #0cb8e170;
    }
    .tool-icon {
      width: 48px;
      height: 48px;
      background-image: url(/static/icon/poi.png);
      background-size: 100% 100%;
    }
  }
  .selectBh {
    width: 150px;
    min-height: 70px;
    top: 302px;
    left: -140px;
  }
  .historyDz {
    width: 400px;
    min-height: 470px;
    top: 10px;
    left: -387px;
  }

  .specialMap {
    width: 230px;
    top: 10px;
    left: -218px;
    max-height: calc(100vh - 135px);
    overflow: auto;
    // 滚动条整体部分
    &::-webkit-scrollbar {
      width: 6px;
      height: 8px;
    }
    &::-webkit-scrollbar-button {
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #01c2ff;
      cursor: pointer;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-corner {
      display: none;
    }
    &::-webkit-resizer {
      display: none;
    }
  }

  .shock-list {
    width: 440px;
    padding: 10px;
    box-sizing: border-box;
    height: 500px;
    top: 108px;
    left: -430px;
  }
  .xcdc {
    width: 150px;
    height: 150px;
    bottom: 0;
    left: -140px;
    padding: 10px;
    li {
      list-style: none;
      display: flex;
      align-items: center;
      text-align: left;
      margin-top: 5px;
      span {
        margin-left: 10px;
      }
    }
  }
}
:deep(.el-popper) {
  background-color: transparent;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
}
.cmap {
  background-color: transparent;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
}
.el-popper {
  display: flex;
}
.active {
  background-color: rgb(0, 25, 51);
  box-shadow: 0 0 10px #1678e1;
}
.t2,
.t3 {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  img {
    width: 70%;
    object-fit: contain;
  }
}
.addZoom,
.eddZoom {
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  font-size: 30px;
  color: #fff;
  font-weight: bold;
  text-align: center;
  align-items: center;
  cursor: pointer;
}

.tool-b {
  position: fixed;
  right: 40px;
  bottom: 35px;
  z-index: 1;
  .pop {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url('/static/assets/3d/rance.png');
    background-size: 100% 100%;
    margin-left: 5px;
    cursor: pointer;
    margin-bottom: 10px;
    img {
      width: 30px;
      object-fit: contain;
    }
  }
  .tool-list {
    position: absolute;
    width: 220px;
    bottom: 60px;
    left: -235px;
    background: rgba(0, 0, 10, 0.8);
    box-sizing: border-box;
    border: 1px solid #0e9cff;
    box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  }
  .selectMap {
    position: absolute;
    background: rgba(0, 0, 10, 0.8);
    box-sizing: border-box;
    border: 1px solid #0e9cff;
    box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
    width: 400px;
    bottom: 10px;
    left: -405px;
  }
  .selectMaps {
    position: absolute;
    background: rgba(0, 0, 10, 0.8);
    box-sizing: border-box;
    border: 1px solid #0e9cff;
    box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
    width: 180px;
    bottom: 108px;
    left: -185px;
    padding: 20px;
    box-sizing: border-box;
    justify-content: space-around;
    div:hover {
      background-color: rgb(0, 25, 51);
      box-shadow: 0 0 10px #1678e1;
    }
  }
  .home {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url(/static/assets/3d/rance.png);
    background-size: 100% 100%;
    margin-left: 5px;
    margin-bottom: 10px;
    cursor: pointer;
    div {
      width: 30px;
      height: 30px;
      background-image: url(/static/assets/3d/home.png);
      background-size: 100% 100%;
    }
  }
  .item-gj,
  .item-dt {
    width: 48px;
    height: 48px;
    background-size: 100% 100%;
    cursor: pointer;
  }
  .item-gj {
    background-image: url(/static/assets/3d/gj.png);
    background-size: 45px 45px;
    background-position: center;
    background-repeat: no-repeat;
  }
  .item-dt {
    background-image: url(/static/assets/3d/dt.png);
  }
}

.ycss {
  position: absolute;
  // background-color: rgb(0, 25, 51);
  // border: 1px solid #0e9cff;
  // box-shadow: 0 0 10px #1678e1;
  border-radius: 8px;
  bottom: 0;
  left: -387px;
  /* height: 100px; */
  width: 400px;
}
</style>